package com.thl.service.impl;


import com.thl.mapper.UserMapper;
import com.thl.pojo.User;
import com.thl.service.UserService;
import com.thl.utils.ConstantKit;
import com.thl.utils.Md5TokenGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service("userService")
public class UserServiceImpl implements UserService {


    @Autowired
    private UserMapper userMapper;

    @Autowired
    private StringRedisTemplate redis;

    @Autowired
    Md5TokenGenerator Md5TokenGenerator;

    @Override

    @Transactional(propagation = Propagation.SUPPORTS)
    public Map<String, Object> userLogin(String uname, String upwd) throws Exception {
        Map<String, Object> requestMap = new HashMap<>();
        User user = userMapper.userLogin(uname);
        if (user == null || user.getId() == null) {
            requestMap.put("code", 301);
            requestMap.put("message", "用户不存在");

        }
        if (upwd != null && upwd.equals(user.getPassword())) {//密码正确
            String tokenKey = Md5TokenGenerator.generate(uname, upwd);
            //添加tockne时间为60分钟
            redis.opsForValue().set(tokenKey, user.getId().toString(), ConstantKit.TOKEN_LOGIN_TIME, TimeUnit.SECONDS);
            requestMap.put("code", 200);
            requestMap.put("message", "登录成功" + user);
            requestMap.put("tokenKey", tokenKey);
            System.out.println("value:" + redis.opsForValue().get(tokenKey));
            return requestMap;
        } else {
            requestMap.put("code", 302);
            requestMap.put("message", "登录失败密码错误");
        }
        requestMap.put("code", 303);
        requestMap.put("message", "登录失败");

        return requestMap;
    }
}
